/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package  org.mitre.lattice.taglib;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.mitre.lattice.query.LatticeQuery;
import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.DBMetaData;
import org.mitre.mrald.util.Link;
import org.mitre.mrald.util.MraldConnection;
import org.mitre.mrald.util.MraldException;
import org.mitre.mrald.util.MraldOutFile;
import org.mitre.mrald.util.*;
/**
 *  Description of the Class
 *
 *@author     ghamilton
 *@created    JUly 20th, 2004
 */
public class LatticeDropDownListTag extends TagSupport
{

	private String table = "";
    private String listColumn = "";
    private String pkColumn = "";
    private String value = "";
	private String filterColumnValue="";
	private String filterColumn="";
	private String filterTable;
	private User user = null;
    private String datasource = "";

	/**
	 *  Constructor for the AllTablesListTag object
	 */
	public LatticeDropDownListTag()
	{
		super();

	}


	/**
     *  Gets the dropDown attribute of the DropDownListTag object
     *
     *@return                   The dropDown value
     *@exception  JspException  Description of the Exception
     */
    public String getDropDown()
        throws JspException
    {
        try
        {
            MraldConnection conn = new MraldConnection( datasource );

            /*
             *  some databases allow spaces in a table name.
             *  Check here and put double quotes (") around any table name
             *  Check to make sure the quotes aren't already there, as well
             */
            if ( table == null) return "";

            if ( table.indexOf( " " ) > 0 && table.charAt( 0 ) != '"' )
            {
                table = "\"" + table + "\"";
            }

            String tableList = table;
            String whereClause = "";

            if (!filterColumn.equals("") && !filterColumnValue.equals(""))
            {
            	String linkStr ="";
            	whereClause += " Where " + filterColumn + " = '" + filterColumnValue + "'";
            	if (filterTable != null)
            	{
            		linkStr = getLink(table, filterTable);
            		whereClause += " AND " + linkStr;
            		tableList += ", " + filterTable + " ";
            	}
            }
            String select = "Select DISTINCT " + table + "." + pkColumn + " as id," + table + "." + listColumn + " from " + tableList + whereClause + " order by " + listColumn;
    	    user = (User) pageContext.getSession().getAttribute(Config.getProperty("cookietag"));

    	    if ( Config.useLattice() )
    		    select =  appendToQuery(select);

    	    MraldOutFile.logToFile( Config.getProperty( "LOGFILE" ), "LatticeDropDownLnListTag: " + select );

            ResultSet rs = conn.executeQuery( select );
            ResultSetMetaData rsmd = rs.getMetaData();
            StringBuffer buffer = new StringBuffer();
            while ( rs.next() )
            {
                String entry = rs.getString( 1 );
                if( entry==null )
                {
                    continue;
                }
                buffer.append( "\n<option value=\"" + entry + "\"" );
                if ( String.valueOf(entry).equals( value ) )
                {
                    buffer.append( " selected=\"selected\"" );
                }
                buffer.append( ">" );
                for ( int i = 2; i < ( rsmd.getColumnCount() + 1 ); i++ )
                {
                    buffer.append( rs.getString( i ) );
                    if ( i != rsmd.getColumnCount() )
                    {
                        buffer.append( " - " );
                    }
                }
                buffer.append( "</option>" );
            }
            rs.close();
            conn.close();
            return buffer.toString();

        }
        catch ( SQLException e )
        {
            JspException se = new JspException( e );
            throw se;
        }
        catch ( MraldException e )
        {
            JspException se = new JspException( e );
            throw se;
        }
    }


    // Copied verbatim from DropDownListTag: Why doesn't this drop down extend the other one?
    private String getLink(String table1, String table2) throws MraldException
    {
    	DBMetaData md = MetaData.getDbMetaData(datasource);

    	//Check case
    	if ( (table1.toUpperCase()).equals((table2).toUpperCase()) )
    		return "";
    	try
    	{
    	ArrayList links = md.getLinks(table1, table2);
    	String rtnStr= "";
    	for (int i=0; i < links.size(); i++)
    	{
    		Link link = (Link)links.get(i);
    		if (i > 0)
    			rtnStr += " AND ";

    		rtnStr += link.toString();

    	}


    	return rtnStr;
    	}
    	catch(MraldException me)
    	{
    		return "";
    	}

    }


    /**
     *  Standard starting point in the TagSupport class. Overridden to create
     *  custom functionality.
     *
     *@return                   Description of the Return Value
     *@exception  JspException  Description of the Exception
     */
    public int doStartTag()
        throws JspException
    {
        try
        {

            pageContext.getOut().print( getDropDown() );
            return EVAL_BODY_INCLUDE;
        }
        catch ( IOException e )
        {
            JspException se = new JspException( e );
            throw se;
        }
    }
	/**
     *@param  tableName  To allow for any additional processing
     */
    protected String appendToQuery( String query )  throws MraldException
    {

//		    LatticeQuery latQuery = new LatticeQuery();

		    String newQuery =  LatticeQuery.adaptQuery(query, user);

		    return  newQuery;
    }

     /**
     *@param  tableName  The new table value
     */
    public void setTable( String tableName )
    {
        this.table = tableName;
    }


    /**
     *@param  value  The new value value
     */
    public void setValue( String value )
    {
        this.value = value;
    }


    /**
     *@param  listColumn  The new listColumn value
     */
    public void setListColumn( String listColumn )
    {
        this.listColumn = listColumn;
    }


    /**
     *@param  pkColName  The new pkColumn value
     */
    public void setPkColumn( String pkColName )
    {
        this.pkColumn = pkColName;
    }

    /**
     *@param  value  The new value value
     */
    public void setFilterColumnValue( String filterColumnValue)
    {
        this.filterColumnValue = filterColumnValue;
    }

    /**
     *@param  value  The new value value
     */
    public void setFilterColumn( String filterColumn)
    {
        this.filterColumn = filterColumn;
    }

    /**
     *@param  value  The new value value
     */
    public void setFilterTable( String filterTable)
    {
        this.filterTable = filterTable;
    }

    public void setDatasource( String ds )
    {
        this.datasource = ds;
    }

}
